package com.by.charpter03.broadcast;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.by.charpter03.R;

import androidx.appcompat.app.AppCompatActivity;

public class BroadcastActivity extends AppCompatActivity implements View.OnClickListener {
    MyBroadcastReceiver mReceiver;
    TextView msg;
    String msgInfo = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broadcast);
        msg = findViewById(R.id.msg);
        findViewById(R.id.regist).setOnClickListener(this);
        findViewById(R.id.unregist).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist:
                registBroadcast();
                break;
            case R.id.unregist:
                unregisterReceiver();
                break;
        }

    }

    private void unregisterReceiver() {
        unregisterReceiver(mReceiver);
    }

    private void registBroadcast() {
        IntentFilter filter = new IntentFilter("action_friend");
        registerReceiver(mReceiver, filter);


    }

    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String name = intent.getStringExtra("name");
            msgInfo += (name + "\n");
            msg.setText(msgInfo);
        }
    }


}
